import { ArticleDetail, CommentRes } from '@/types/data'
import { ArticleAction } from '@/types/store'

type ArticleState = {
  info: ArticleDetail
  comment: CommentRes
  reply: CommentRes
}

const initialState = {
  info: {},
  comment: {},
  reply: {}
} as ArticleState

export default function articleReducer(
  state = initialState,
  action: ArticleAction
): ArticleState {
  if (action.type === 'article/set_article_detail') {
    return {
      ...state,
      info: action.payload
    }
  }

  if (action.type === 'article/set_comment') {
    // const oldComment = state.comment.results || []
    return {
      ...state,
      comment: action.payload
    }
  }

  if (action.type === 'article/save_new_comment') {
    return {
      ...state,
      comment: {
        ...state.comment,
        results: [action.payload, ...state.comment.results]
      }
    }
  }

  if (action.type === 'article/save_reply') {
    // const old = state.reply.results || []

    return {
      ...state,
      reply: action.payload
    }
  }

  return state
}
